﻿@using Enter.Admin.Utils
@using Enter.Admin.Enums
@using Enter.Admin.Dtoes
@using Enter.Admin.Entities
@using Enter.Admin.Models.DataTables
@model CaseIndexModel
@{
    ViewData["Title"] = Model.Title;

    var enum_feild_map = new Dictionary<string, string>();

    var columns_SelectListItem = new List<SelectListItem>() { new SelectListItem { Text = "请选择", Value = "" } };
    var columns_Date_SelectListItem = new List<SelectListItem>() { new SelectListItem { Text = "请选择", Value = "" } };
    var columns_Enum_SelectListItem = new List<SelectListItem>() { new SelectListItem { Text = "请选择", Value = "" } };
    foreach (var item in Model.Columns.Where(t => t.searchable))
    {
        var select_item = new SelectListItem { Text = item.title, Value = item.data };
        if (item.dataType == "DateTime")
        {
            columns_Date_SelectListItem.Add(select_item);
        }
        else if (!string.IsNullOrWhiteSpace(item.drop))
        {
            columns_Enum_SelectListItem.Add(select_item);
            enum_feild_map.Add(item.data, item.drop);
        }
        else
        {
            columns_SelectListItem.Add(select_item);
        }
    }
}
@section Styles {
    <link href="~/plugins/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-fixedcolumns-bs4/css/fixedColumns.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-select/css/select.dataTables.min.css" rel="stylesheet" />
    @*<link href="~/plugins/datatables.net-select-bs4/css/select.bootstrap4.min.css" rel="stylesheet" />*@
    <link href="~/plugins/dropzone/dist/min/dropzone.min.css" rel="stylesheet" />
    <link href="~/plugins/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet" />
    <link href="~/plugins/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet" />
    <link href="~/plugins/jquery-transfer/icon_font/css/icon_font.css" rel="stylesheet" />
    <link href="~/plugins/jquery-transfer/css/jquery.transfer.css" rel="stylesheet" />
    <style>
        div .bootstrap-select .btn.bs-placeholder {
            color: rgb(0,0,0) !important
        }

        div .bootstrap-select .btn.bs-placeholder:active, div .bootstrap-select .btn.bs-placeholder:focus, div .bootstrap-select .btn.bs-placeholder:hover {
            color: rgb(0,0,0) !important
        }

        div .bootstrap-select .btn.btn-light, div .bootstrap-select .btn.btn-white {
            color: rgb(0,0,0) !important
        }

        .btn-white:not(:disabled):not(.disabled).active, .btn-white:not(:disabled):not(.disabled):active, .show > .btn-white.dropdown-toggle {
            color: rgb(255,255,255) !important
        }

        #data-table-default {
            width: 100% !important;
        }
    </style>
}
@section Scripts {
    <script src="~/plugins/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="~/plugins/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="~/plugins/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
    <script src="~/plugins/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-fixedcolumns/js/dataTables.fixedColumns.min.js"></script>
    <script src="~/plugins/datatables.net-fixedcolumns-bs4/js/fixedColumns.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-select/js/dataTables.select.min.js"></script>
    <script src="~/plugins/datatables.net-select-bs4/js/select.bootstrap4.min.js"></script>
    <script src="~/plugins/dropzone/dist/min/dropzone.min.js"></script>
    <script src="~/plugins/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
    <script src="~/plugins/moment/min/moment.min.js"></script>
    <script src="~/plugins/bootstrap-daterangepicker/daterangepicker.js"></script>
    <script src="~/plugins/jquery-transfer/js/jquery.transfer.js?v=0.0.6"></script>
    <script src="~/plugins/sweetalert/dist/sweetalert.min.js"></script>
    <script>
        var pageStart = parseInt(getQueryString("pageStart"));
        var pageLength = parseInt(getQueryString("pageLength"));
        if (!pageStart) {
            pageStart = 0;
        }
        if (!pageLength) {
            pageLength = 10;
        }
        var CaseType = @((int)Model.CaseType);
        var objectType = @((int)EnumAttachmentObjectType.档案附件);
        var searchObj = function () {
            var dy_searchs = []
            $("[id^='SearchStringField_']").each(function (index, value) {
                dy_search_model = {
                    SearchStringField: $($("[id^='SearchStringField_']")[index]).val(),
                    SearchStringOperator: $($("[id^='SearchStringOperator_']")[index]).val(),
                    SearchStringValue: $($("[id^='SearchStringValue_']")[index]).val(),
                    SearchDateField: $($("[id^='SearchDateField_']")[index]).val(),
                    SearchDateValue: $($("[id^='SearchDateValue_']")[index]).val(),
                    SearchEnumField: $($("[id^='SearchEnumField_']")[index]).val(),
                    SearchEnumValue: $($("[id^='SearchEnumValue_']")[index]).val().join(','),
                }
                dy_searchs.push(dy_search_model)
            });
            return {
                CaseType: CaseType,
                Id: Number($('#Id').val()),
                BusinessNo: $('#BusinessNo').val(),
                ContractNo: $('#ContractNo').val(),
                DynamicSearchs: dy_searchs,
                FullText: $('.dataTables_filter input').val(),
            }
        }
        var enum_feild_map = @Html.Raw(Jsons.Serialize(enum_feild_map));
        var all_enums = @Html.Raw(Jsons.Serialize(EnumsExt.EnumMap));

        var all_columns = @Html.Raw(Jsons.Serialize(Model.Columns));

        var transfer = null
        // 删除
        var delete_case_ajax = function () {
            var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
            if (rows.length == 0) {
                show_alert('warning', "请选择.")
                return
            }
            swal({
                title: '确定删除?',
                text: '删除后将无法恢复!',
                icon: 'warning',
                buttons: {
                    cancel: {
                        text: '取消',
                        value: null,
                        visible: true,
                        className: 'btn btn-default',
                        closeModal: true,
                    },
                    confirm: {
                        text: '删除',
                        value: true,
                        visible: true,
                        className: 'btn btn-warning',
                        closeModal: true
                    }
                }
            }).then((willDelete) => {
                if (willDelete) {
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json;charset=utf-8",
                        data: JSON.stringify({ Ids: rows }),
                        url: "@Url.Action("Delete", "Case")",
                        success: function (result) {
                            if (result.Success) {
                                $("#search-button").click()
                                show_alert('success', result.Message)
                            } else {
                                show_alert('warning', result.Message)
                            }
                        },
                        error: function (e) {
                            show_alert('error', '网络异常.')
                        }
                    });
                }
            });
        }

        var case_allocation = function () {
            var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
            if (rows.length == 0) {
                show_alert('warning', "请选择需要分配的案件.")
                return
            }
            $("#modal-dialog-allocation").modal()
        }
        var case_allocation_ajax = function () {
            $("#modal-dialog-allocation-button").click(function () {
                var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
                var data = {
                    ArchiveIds: rows,
                    ChargeUserId: $("#AllocationUser").val()
                }
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    data: JSON.stringify(data),
                    url: "@Url.Action("Allocation", "Home")",
                    success: function (result) {
                        if (result.Success) {
                            $("#search-button").click()
                            $("#modal-dialog-allocation").modal('hide')
                            show_alert('success', result.Message)
                        } else {
                            show_alert('warning', result.Message)
                        }
                    },
                    error: function (e) {
                        show_alert('error', '网络异常.')
                    }
                });
            })
        }

        // https://www.cnblogs.com/chiakiyu/p/5436899.html
        var dataTable = null
        var params_table = null
        var handleDataTableDefault = function () {
            var columns = all_columns.slice()
            if (!isMobile) {
                columns.unshift({ title: '<input class="checkbox_all" type="checkbox"/>', orderable: false })
            }
            //columns[0].title = '<input class="checkbox_all" type="checkbox"/> 序号'
            columns.push({ data: "Id", title: '操作',  orderable: false })

            params_table = {
                    dom: 'lBfrtip',
                    buttons: [
                        {
                            text: '导入 <i class="fa fa-file-import"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                resetDropzone(0);
                                $('#modal-dialog-dropzone-import').modal();
                            }
                        },
                        {
                            text: '导出 <i class="fa fa-file-export"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                transfer_export();
                            }
                        },
                        {
                            text: '分配负责人 <i class="fas fa-thumbtack"></i>',
                            className: 'btn btn-primary',
                            action: function (e, dt, node, config) {
                                case_allocation()
                            }
                        },
                        {
                            text: '上传附件 <i class="fa fa-upload"></i>',
                            className: 'btn btn-primary',
                            action: function (e, dt, node, config) {
                                var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
                                if (rows.length == 0) {
                                    show_alert('warning', "请选择案件")
                                    return;
                                }
                                $('#modal-dialog-dropzone-attachment').modal();
                            }
                        },
                        {
                            text: '新增 <i class="fa fa-plus"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                var add_url="@Url.Action("Add", "Case")" + "/" + CaseType;
                                window.open(add_url, '_blank');
                                //window.location.href = add_url fa fa-upload
                            }
                        },
                        {
                            text: '删除 <i class="fa fa-minus"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                delete_case_ajax()
                            }
                        }
                    ],
                    responsive: isMobile, //是否显示全部
                    "searching": true,//datatables自带的搜索
                    "processing": true,//加载中
                    "serverSide": true,
                    //"scrollX": true,
                    //"sScrollX": true,
                    "autoWidth": false,
                    //fixedColumns: {
                    //    leftColumns: 2,
                    //    rightColumns: 1,
                    //    "drawCallback": function () {
                    //        $(".DTFC_Cloned").css("width", "auto")
                    //        $(".DTFC_RightBodyLiner").css("overflow-y", "hidden")
                    //    }
                    //},
                    // 下一页更新复选框为不选中.
                    //fnDrawCallback: function () {
                    //    $('.checkbox_select').removeAttr("checked");
                    //    $('.checkbox_all').removeAttr("checked");
                    //},
                    "lengthMenu": [10, 50, 100, 200, 500],
                    "displayStart": pageStart,
                    "pageLength": pageLength,
                    "ajax": {
                        type: "POST",
                        url: '@Url.Action("Index", "Case")',
                        contentType: "application/json; charset=utf-8",
                        async: true,
                        headers: {
                            // https://www.cnblogs.com/liek/p/4884154.html
                           // "XSRF-TOKEN": document.querySelector('[name="__RequestVerificationToken"]').value
                            //"__RequestVerificationToken": $('[name="__RequestVerificationToken"]').val()
                        },
                        data: function (data) {
                            startSize = data.start
                            pageLength = data.length
                            changeURLState("pageStart", data.start)
                            changeURLState("pageLength", data.length)
                            // 请求参数;
                            data.Data = searchObj()
                            data.columns = []
                            //data.__RequestVerificationToken = $('[name="__RequestVerificationToken"]').val()
                            return JSON.stringify(data);
                        }
                        //,
                        //"data": function (data) {
                        //    data.Name = $("#name").val();//此处是添加额外的请求参数
                        //    return JSON.stringify(data);
                        //}
                    },
                    //rowId: 'Id',
                    columns: columns,
                    //select: {
                    //    style: 'multi',
                    //    selector: 'td:first-child',//'td:first-child' 'td:not(:last-child)'
                    //    //blurable: true
                    //},
                    "columnDefs": [
                        //{
                        //    orderable: false,
                        //    className: 'select-checkbox',
                        //    targets: 0,
                        //    render: function (data, type, full, meta) {
                        //        return '';
                        //    }
                        //},
                        {
                            "targets": 1,
                            //className: 'select-checkbox',
                            render: function (data, type, full, meta) {
                                //return '<input class="checkbox_select" value = "' + full.Id + '" type="checkbox"/> ';// + full.Id;
                                //return '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Detail", "Case")/' + full.Id + '">详情 <i class="fa fa-info"></i></a> ' + data;
                                return '<a target="_blank" href="@Url.Action("Detail", "Case")/' + full.Id + '">' + data+'</a> ';
                            }
                        },
                        {
                            "targets": -1,//-1表示最后一行 也可以是数组，"visible": false,"searchable": false
                            //"width": "220px",
                            render: function (data, type, full, meta) {
                                return '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Detail", "Case")/' + full.Id + '">详情 <i class="fa fa-info"></i></a>  '
                                    + '<a class="btn btn-sm btn-info" target="_blank" href="@Url.Action("Edit", "Case")/' + full.Id + '">修改 <i class="fa fa-edit"></i></a> ';
                            }
                        }
                    ],
                    "language": datatable_language
                }
            if (!isMobile) {
                //params_table.fixedColumns = {
                //    //leftColumns: 2,
                //    rightColumns: 1,
                //    "drawCallback": function () {
                //        $(".DTFC_Cloned").css("width", "auto")
                //        $(".DTFC_RightBodyLiner").css("overflow-y", "hidden")
                //    }
                //}
                params_table.select = {
                    style: 'multi',
                    selector: 'td:first-child',//'td:first-child' 'td:not(:last-child)' '.DTFC_LeftBodyWrapper td:first-child'
                    //blurable: true
                }
                params_table.columnDefs.unshift({
                    orderable: false,
                    className: 'select-checkbox',
                    "width": "15px",
                    targets: 0,
                    render: function (data, type, full, meta) {
                        return '';
                    }
                })

            }
            // dataTable.ajax.params();
            // dataTable.page.info(); https://datatables.net/reference/api/page.info()
            dataTable = $('#data-table-default').DataTable(params_table);
            //dataTable.columns.adjust()
            // 取消datatabel的水平动作条，使用wrapAll在table上再包装一层div
            if (!isMobile) {
                $("#data-table-default").wrapAll("<div style='overflow-x:auto'>");
            }

        };

        function filesParamName() {
            return "files";
        }
        Dropzone.autoDiscover = false;
        var dropzone_pre_file = null;
        var resetDropzone = function () {
             // http://www.voidcn.com/article/p-huweyrcj-bvo.html
            // http://www.renfei.org/blog/dropzone-js-introduction.html
            // https://stackoverflow.com/questions/31380478/reinitialize-reset-dropzone-after-form-is-submitted?noredirect=1
            dropzone_pre_file = null;
            $('#dropzone-container-import').empty();
            $('#dropzone-container-import').html($('#dropzone_template').html())
            $("#dropzone-upload-import").dropzone({
                maxFiles: 1,
                url: "@Url.Action("Upload", "Case")",
                method: "post",
                acceptedFiles: ".xlsx",
                paramName: filesParamName,
                addRemoveLinks: true,
                uploadMultiple: false,
                init: function () {
                    settlmentProofDropZone = this;
                    this.on("addedfile", function (file) {
                        if (dropzone_pre_file != null) {
                            this.removeFile(dropzone_pre_file);
                        }
                        dropzone_pre_file = file
                    });
                    this.on("success", function (file, resp) {
                        // 上传完成后触发的方法
                        if (resp.Success) {
                            $('#dropzone-upload-input').val(resp.Data)
                        } else {
                            $('#dropzone-upload-input').val('')
                            if (dropzone_pre_file != null) {
                                this.removeFile(dropzone_pre_file);
                            }
                            dropzone_pre_file = null
                            show_alert('warning', resp.Message)
                        }
                    });
                    this.on("removedfile", function (file) {
                        // 删除文件时触发的方法
                        dropzone_pre_file = null
                        $('#dropzone-upload-input').val('')
                    });
                }
            });
        }

        var settlmentProofDropZoneAttachment = null
        var dropzone_container_upload_attachment = function () {
            $("#dropzone-upload-attachment").dropzone({
                maxFiles: 5,
                url: "@Url.Action("Upload", "Attachment")",//  + "?objectId=" + objectId + "&objectType=" + objectType
                method: "post",
                acceptedFiles: "",
                paramName: filesParamName,
                addRemoveLinks: true,
                uploadMultiple: true,
                init: function () {
                    settlmentProofDropZoneAttachment = this;
                    this.on("sending", function (file, xhr, data) {
                        var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
                        data.append("objectIds", rows.join(','));
                        data.append("objectType", objectType);
                        data.append("catalogType", $("#CatalogType").val());
                    });
                    this.on("success", function (file, resp) {
                        if (resp.Success) {
                            //dataTable.ajax.reload();
                            show_alert('success', resp.Message)
                            $('#modal-dialog-dropzone-attachment').modal('hide')
                        } else {
                            show_alert('warning', resp.Message)
                        }
                        this.removeAllFiles();
                    });
                }
            });
        }

        // 导入;
        var import_excel = function () {
            var file_name = $('#dropzone-upload-input').val()
            if (!file_name) {
                show_alert('warning', '请选择文件.')
            } else {
                show_ajax();
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    url: "@Url.Action("Import", "Case")",
                    data: JSON.stringify({
                        FileName: file_name,
                        CaseType: CaseType,
                    }),
                    success: function (result) {
                        hide_ajax()
                        if (result.Success) {
                            show_alert('success', result.Message)
                            $('#dropzone-upload-input').val('')
                            $('#modal-dialog-dropzone-import').modal('hide')

                            // user paging is not reset on reload
                            dataTable.ajax.reload(null, false)
                            //$("#search-button").click()
                        } else {
                            show_alert('warning', result.Message)
                            if (result.Data) {
                                window.open("@Url.Action("Download", "Case")" + "?filename=" + result.Data)
                            }
                        }
                    },
                    error: function (e) {
                        hide_ajax()
                        show_alert('error', '网络异常.')
                    },
                    complete: function (XMLHttpRequest, status) {
                        hide_ajax()
                    }
                });
            }
        }

        var default_selected = []// ["Id", "ContractNo"]
        var transfer_export = function () {
            var dataArray = []
            //var columns = all_columns.slice()
            for (let i = 0; i < all_columns.length; i++) {
                var item = all_columns[i]
                if (item.export) {
                    dataArray.push({
                        "data": item.data,
                        "title": item.title,
                        "selected": default_selected.includes(item.data)
                    })
                }
            }
            var settings1 = {
                "dataArray": dataArray,
                "itemName": "title",
                "valueName": "data",
                tabNameText: "未选择的项",
                rightTabNameText: "已选择的项",
                searchPlaceholderText: "搜索",
                //"callable": function (items) {
                //    console.dir(items)
                //}
            };
            $("#transfer-export").empty()
            transfer = $("#transfer-export").transfer(settings1);
            $('#modal-dialog-export').modal();
        }

        var export_excel_button = function () {
            var columns = transfer.getSelectedItems().map(({ data }) => (data));
            var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => (Id));
            // var rows = dataTable.rows({ selected: true }).data().toArray().map(({ Id }) => ({ Id }));

            var data = {
                Data: searchObj(),
                Columns: columns,
                Rows: rows
            }
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: "@Url.Action("Export", "Case")",// ,new {id = Model.Id }
                data: JSON.stringify(data),
                success: function (result) {
                    if (result.Success) {
                        window.location.href = "@Url.Action("Export", "Case")" + "/" + result.Data
                        $('#modal-dialog-export').modal('hide')
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
        }

        var date_range_select = function (daterangepicker_id1) {
            $(daterangepicker_id1).daterangepicker({
                format: 'YYYY-MM-DD',
                autoUpdateInput: false,
                //startDate: moment().subtract(29, 'days'),
                //endDate: moment(),
                minDate: '1970-01-01',
                maxDate: '2050-12-31',
                //dateLimit: { days: 60 },
                //showDropdowns: true,
                //showWeekNumbers: true,
                alwaysShowCalendars:true,
                timePicker: false,
                timePickerIncrement: 1,
                timePicker12Hour: false,
                ranges: {
                    '今天': [moment(), moment()],
                    '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    '最近一周': [moment().subtract(6, 'days'), moment()],
                    '这个月': [moment().startOf('month'), moment().endOf('month')],
                    '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                },
                opens: 'right',
                drops: 'down',
                buttonClasses: ['btn', 'btn-sm'],
                applyClass: 'btn-primary',
                cancelClass: 'btn-default',
                separator: ' to ',
                locale: {
                    format: 'YYYY-MM-DD',
                    applyLabel: '确定',
                    cancelLabel: '清除',
                    fromLabel: 'From',
                    toLabel: 'To',
                    customRangeLabel: '自定义',
                    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                    firstDay: 1
                }
            }, function (start, end, label) {
                    $(daterangepicker_id1).val(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
            });
            $(daterangepicker_id1).on('cancel.daterangepicker', function (ev, picker) {
                //做点什么，比如清除输入
                $(daterangepicker_id1).val('');
            });
        }

        var select_enum_change = function (changeFrom, changeTo) {
            $(changeFrom).change(function () {
                $(changeTo).empty();
                var s_v = $(this).val();
                if (s_v != "") {
                    var arr = all_enums[enum_feild_map[s_v]]

                    for (j = 0; j < arr.length; j++) {
                        var option = $("<option>").val(arr[j]["Value"]).text(arr[j]["Text"]);
                        $(changeTo).append(option);
                    }
                }
                //else {
                //    var option = $("<option>").val("").text("请选择");
                //    $("#SearchEnumValue").append(option);
                //}
                $(changeTo).selectpicker('refresh');
            });
        }

        var dynamic_search_count = 0
        var minus_dynamic_search = function () {
            if (dynamic_search_count > 0) {
                var dynamic_search_row_id = "dynamic_search_row_" + dynamic_search_count;
                // 删除
                $("#" + dynamic_search_row_id).remove();
                dynamic_search_count--;
            }
        }
        var plus_dynamic_search = function () {
            dynamic_search_count++;
            var dynamic_search_row_id = "dynamic_search_row_" + dynamic_search_count;
            var SearchDateValueId = "SearchDateValue_" + dynamic_search_count;
            var SearchEnumFieldId = "SearchEnumField_" + dynamic_search_count;
            var SearchEnumValueId = "SearchEnumValue_" + dynamic_search_count;
            var addHtml = $("#dynamic_search_template").html()
                .replaceAll("dynamic_search_row", dynamic_search_row_id)
                .replaceAll("SearchStringField", "SearchStringField_" + dynamic_search_count)
                .replaceAll("SearchStringValue", "SearchStringValue_" + dynamic_search_count)
                .replaceAll("SearchStringOperator", "SearchStringOperator_" + dynamic_search_count)
                .replaceAll("SearchDateField", "SearchDateField_" + dynamic_search_count)
                .replaceAll("SearchDateValue", SearchDateValueId)
                .replaceAll("SearchEnumField", SearchEnumFieldId)
                .replaceAll("SearchEnumValue", SearchEnumValueId)
            $(".dynamic_search").append(addHtml)
            $('#' + dynamic_search_row_id+' .selectpicker').selectpicker('render');
            date_range_select('#' + SearchDateValueId);
            select_enum_change('#' + SearchEnumFieldId, '#' +SearchEnumValueId);
        }

        $(document).ready(function () {
            handleDataTableDefault();
            // https://developer.snapappointments.com/bootstrap-select/options/
            $('.selectpicker').selectpicker('render');
            dropzone_container_upload_attachment()
            //date_range_select('#SearchDateValue');
            //select_enum_change("#SearchEnumField", "#SearchEnumValue");
            case_allocation_ajax();
            $("#dropzone-upload-button-import").click(function () {
                import_excel();
            });

            $("#search-button").click(function () {
                if (dataTable != null) {
                    //dataTable.ajax.reload();
                    dataTable.search($('.dataTables_filter input').val()).draw();

                    // user paging is not reset on reload
                    //dataTable.ajax.reload(null, false)
                }
            });

            $("#export-button").click(function () {
                export_excel();
            });

            $("#modal-dialog-export-button").click(function () {
                export_excel_button();
            });

            $(".search-button-minus").click(function () {
                minus_dynamic_search()
            })
            $(".search-button-plus").click(function () {
                plus_dynamic_search()
            })

            $('.dataTables_filter input').unbind();// .off();

            // https://blog.csdn.net/nihaoqiulinhe/article/details/53412077
            // https://blog.csdn.net/zxc84265137/article/details/83576661
            $("#data-table-default").on("click", ".checkbox_all", function (e) {
                // data-table-default_wrapper
                // ".DTFC_LeftHeadWrapper .checkbox_all"
                if (this.checked) {
                    dataTable.rows().select();
                     //var count = dataTable.rows( { selected: true } ).count();
                    //$('.DTFC_LeftBodyWrapper .checkbox_select').attr("checked", 'true')
                    //$('.checkbox_select').each(function () {
                    //    this.checked = true;
                    //});
                }
                else {
                    dataTable.rows().deselect();
                    //$('.DTFC_LeftBodyWrapper .checkbox_select').removeAttr("checked")
                    //$('.checkbox_select').each(function () {
                    //    this.checked = false;
                    //});
                }
            });
        });

    </script>
}

<script type="text/html" id="dropzone_template">
    <form asp-action="Upload" asp-controller="Case" class="dropzone needsclick" enctype="multipart/form-data" id="dropzone-upload-import">
        <input type="text" id="dropzone-upload-input" style="display:none" class="form-control" />
        <div class="dz-message needsclick">
            点击选择文件
        </div>
    </form>
</script>
<!-- begin breadcrumb -->
@*<ol class="breadcrumb float-xl-right">
    <li class="breadcrumb-item"><a href="javascript:;">资料管理</a></li>
    <li class="breadcrumb-item active">档案管理</li>
</ol>*@
<!-- end breadcrumb -->
<!-- begin page-header -->
@*<h1 class="page-header">档案管理 <small>...</small></h1>*@
<!-- end page-header -->
<!-- begin panel -->
<div class="panel panel-inverse">
    <!-- begin panel-heading -->
    <div class="panel-heading">
        <h4 class="panel-title">档案列表</h4>
    </div>
    <!-- end panel-heading -->
    <div class="panel-body">
        <div class="row m-b-5">
            <div class="col-md-3 m-b-5">
                <div class="input-group">
                    <div class="input-group-prepend"><span class="input-group-text">序号:</span></div>
                    <input type="number" id="Id" class="form-control" />
                </div>
            </div>
            <div class="col-md-3 m-b-5">
                <div class="input-group">
                    <div class="input-group-prepend"><span class="input-group-text">合同编号:</span></div>
                    <input type="text" id="ContractNo" class="form-control" />
                </div>
            </div>
            <div class="col-md-3 m-b-5">
                <div class="input-group">
                    <div class="input-group-prepend"><span class="input-group-text">借据编号:</span></div>
                    <input type="text" id="BusinessNo" class="form-control" />
                </div>
            </div>
            <div class="col-md-3 text-right">
                <!--在Bootstrap 4中，pull-right样式类已经更名为float-right类名了-->
                <!--
            <a href="#modal-dialog" class="btn btn-primary" data-toggle="modal">导入 <i class="fa fa-file-import"></i></a>
            <button type="button" id="export-button" class="btn btn-primary">导出 <i class="fa fa-file-export"></i></button>
            -->
                <button type="button" id="search-button" class="btn btn-primary">搜索 <i class="fas fa-search"></i></button>
                <button type="button" class="btn btn-primary search-button-plus"><i class="fas fa-search-plus"></i></button>
                <button type="button" class="btn btn-primary search-button-minus"><i class="fas fa-search-minus"></i></button>

            </div>
        </div>
        <div class="dynamic_search">

        </div>
        <script type="text/html" id="dynamic_search_template">
            <div class="row search-button-row" id="dynamic_search_row">
                <div class="col-md-4 m-b-5">
                    <div class="input-group">
                        @Html.DropDownList("SearchStringField", columns_SelectListItem, new { @class = "form-control selectpicker", @data_live_search = "true" })
                        <select class="form-control selectpicker" id="SearchStringOperator" data-live-search="true">
                            <option value="Eq">等于</option>
                            <option value="Contains">包含</option>
                            <option value="StartsWith">以开始</option>
                            <option value="EndsWith">以结束</option>
                            <option value="NotContains">不包含</option>
                            <option value="NotEqual">不等于</option>
                            <option value="GreaterThanOrEqual">大于等于</option>
                            <option value="LessThanOrEqual">小于等于</option>
                            <option value="Range">范围</option>
                        </select>
                        <input type="text" class="form-control" id="SearchStringValue" />
                    </div>
                </div>
                <div class="col-md-4 m-b-5">
                    <div class="input-group">
                        @Html.DropDownList("SearchDateField", columns_Date_SelectListItem, new { @class = "form-control selectpicker", @data_live_search = "true" })
                        <input type="text" class="form-control" id="SearchDateValue" />
                    </div>
                </div>
                <div class="col-md-4 m-b-5">
                    <div class="input-group">
                        @Html.DropDownList("SearchEnumField", columns_Enum_SelectListItem, new { @class = "form-control selectpicker", @data_live_search = "true" })
                        <select multiple class="form-control selectpicker" id="SearchEnumValue" data-live-search="true" data-none-selected-text="请选择" data-style="btn-white">
                            @*<option value="">请选择</option>*@
                        </select>
                        <!---->
                    </div>
                </div>
            </div>
        </script>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-dropzone-import" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">上传</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="dropzone-container-import">

                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="dropzone-upload-button-import" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-dropzone-attachment" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">上传附件</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="input-group">
                            @Html.DropDownList("CatalogType", Tools.EnumList(nameof(EnumAttachmentCatalogType), false), new { @class = "form-control selectpicker", @data_live_search = "true" })
                        </div>
                        <div id="dropzone-container">
                            <form asp-action="Upload" asp-controller="Attachment" class="dropzone needsclick" enctype="multipart/form-data" id="dropzone-upload-attachment">
                                <div class="dz-message needsclick">
                                    点击选择文件
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-attachment" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">附件列表</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <input type="text" id="attachment-input-id" style="display:none" class="form-control" />
                        <input type="text" id="attachment-input-name" style="display:none" class="form-control" />
                        <div id="attachment-container">
                            <table id="data-table-attachment" class="table table-striped table-bordered table-td-valign-middle display nowrap" style="width:100%">
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-attachment-button" class="btn btn-primary">上传附件</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-export" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">选择导出项</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="transfer-export" class="transfer-demo"></div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-export-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-allocation" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">分配</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="col-form-label">负责人</label>
                            @Html.DropDownList("AllocationUser", Tools.EnumList(nameof(EnumArchive.EnumEmploy), false), new { @class = "form-control selectpicker", @data_live_search = "true" })
                        </div>

                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-allocation-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-table-allocation" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">分配所属机构</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="col-form-label">所属机构</label>
                            @Html.DropDownList("AllocationTable", Tools.EnumList(nameof(EnumArchive.EnumDynamicTable), false), new { @class = "form-control selectpicker", @data_live_search = "true" })
                        </div>

                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-table-allocation-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- begin panel-body -->
    <div class="panel-body">
        <form id="form-delete" style="display:none">@Html.AntiForgeryToken()</form>
        <table id="data-table-default" class="table table-striped table-bordered table-td-valign-middle display nowrap" style="width:100%">
        </table>
    </div>
    <!-- end panel-body   -->
</div>
<!-- end panel -->
